package com.ohuang.onlytest.floating;

import android.app.Activity;

import java.util.HashMap;
import java.util.Map;

 class FloatingMagnetManager {

    int[] xy ;//初始位置

     ViewBuild viewBuild;
    public FloatingMagnetManager(ViewBuild viewBuild) {
        this.viewBuild=viewBuild;
    }


    private final Map<Activity, FloatingMagnetHelper> map = new HashMap<>();

    private boolean isShowEnable =true;

    public boolean isShowEnable() {
        return isShowEnable;
    }

    public void setShowEnable(boolean showEnable) {
        isShowEnable = showEnable;
        if (!isShowEnable){
            for (Activity activity : map.keySet()) {
                hide(activity);
            }
        }
    }

    public FloatingMagnetHelper attach(Activity activity) {

        FloatingMagnetHelper floatingMagnetHelper = null;
        if (map.containsKey(activity)) {
            floatingMagnetHelper = map.get(activity);
        } else {
            floatingMagnetHelper = new FloatingMagnetHelper(activity, viewBuild);
        }
        map.put(activity, floatingMagnetHelper);
        return floatingMagnetHelper;
    }

    public FloatingMagnetHelper show(Activity activity) {

        FloatingMagnetHelper floatingMagnetHelper = null;
        if (map.containsKey(activity)) {
            floatingMagnetHelper = map.get(activity);
        } else {

            floatingMagnetHelper = new FloatingMagnetHelper(activity, viewBuild);
        }
        map.put(activity, floatingMagnetHelper);
        if (floatingMagnetHelper !=null&& isShowEnable) {
            floatingMagnetHelper.show();
            if (xy!=null) {
                floatingMagnetHelper.setXY(xy);
            }
        }
        return floatingMagnetHelper;
    }

    public FloatingMagnetHelper hide(Activity activity) {
        FloatingMagnetHelper floatingMagnetHelper = null;
        if (map.containsKey(activity)) {
            floatingMagnetHelper = map.get(activity);
            if (floatingMagnetHelper !=null) {
                floatingMagnetHelper.hide();
                if (isShowEnable) {
                    xy = floatingMagnetHelper.getXY();
                }
            }
            return floatingMagnetHelper;
        }
        return null;
    }

    public void onDestroy(Activity activity) {
        if (map.containsKey(activity)) {
            FloatingMagnetHelper remove = map.remove(activity);
            if (remove!=null){
                remove.hide();
                if (isShowEnable) {
                    xy = remove.getXY();
                }
            }
        }

    }


}
